#include "mloop.h"

/* Return Value
 * 0: Still in local
 * 1: Still in local but with better energy
 * 2: New cluster
 * 3: Old cluster with better energy
 * 4: Old cluster with worse energy
 */
int loop_cluster(float threshold)
{
	int i, j, flag;
	float rmsd, rmsd_min, energyavg2;

	calc_pmfscore (&(candidate[nsaves]));

	if (nsaves == 0)
		flag = 2;
	else
	{
		rmsd = calc_rmsd (&(candidate[nsaves]), &(candidate[nsaves - 1]));
		if (rmsd < threshold)
		{
			if (candidate[nsaves].energypmf < candidate2[nsaves - 1].energypmf)
				flag = 1;
			else
				flag = 0;
		}
		else
		{
			flag = 2;
			rmsd_min = rmsd;
			for (i = nsaves - 2; i >= 0; i--)
			{
				rmsd = calc_rmsd (&(candidate[nsaves]), &(candidate[i]));
				if (rmsd < rmsd_min)
				{
					rmsd_min = rmsd;
					if (rmsd_min < threshold)
					{
						if (candidate[nsaves].energypmf < candidate2[i].energypmf)
							flag = 3;
						else
							flag = 4;
						break;
					}
				}
			}
		}
	}

	if (flag == 1)
	{
		memcpy (&candidate2[nsaves - 1], &candidate[nsaves], sizeof (struct candidate));
		candidate2[nsaves - 1].energyavg2 = candidate[nsaves].energy2;
	}
	else if (flag == 2)
	{
		memcpy (&candidate2[nsaves], &candidate[nsaves], sizeof (struct candidate));
		candidate2[nsaves].energyavg2 = candidate[nsaves].energy2;
		repr_num[nsaves] = 1;
		nsaves++;
	}
	else if (flag == 3)
	{
		energyavg2 = candidate2[i].energyavg2;
		memcpy (&candidate2[i], &candidate[nsaves], sizeof (struct candidate));
		candidate2[i].energyavg2 = energyavg2 + candidate[nsaves].energy2;
		repr_num[i] ++;
	}
	else if (flag == 4)
	{
		candidate2[i].energyavg2 += candidate[nsaves].energy2;
		repr_num[i] ++;
	}

	return flag;
}
